//
//  ShareViewController.swift
//  ShareCar
//
//  Created by 李帅 on 2019/2/20.
//  Copyright © 2019 changqingkeji. All rights reserved.
//

import UIKit

class ShareViewController: UIViewController {

    @IBOutlet weak var titleLabel: UILabel!
    
    @IBOutlet weak var contentLabel: UILabel!
    
    var orderId: String?
    
    var scheme: OrderShare.Scheme?
    
    override func viewDidLoad() {
        super.viewDidLoad()

        guard let id = orderId else {
            return
        }
        
        JZLoading.showLoadingWith(toView: self.view)
        OrderShare.scheme(orderId: id, success: { [weak self] data in
            JZLoading.hideLoading()
            self?.scheme = data
            
            self?.titleLabel.text = data?.shareTitle
            self?.contentLabel.text = data?.shareContent
        }) { [weak self] msg in
            JZLoading.hideLoading()
            self?.showError(msg)
        }
    }
    
    @IBAction func share(_ sender: UIButton) {
        guard let s = scheme, let id = orderId else {
            return
        }
        
        let model = Share.shareModel(title: s.shareTitle,
                                     description: s.shareContent,
                                     imageName: s.imagePath,
                                     url: s.shareUrl)

        if !User.isLogin() {
            let vc = userInfoStory.instantiateViewController(withIdentifier: "LoginViewController")
            present(vc, animated: true, completion: nil)
        } else {
            let actionSheet = UIAlertController(title: "请选择分享平台", message: nil, preferredStyle: .actionSheet)
            actionSheet.addAction(UIAlertAction(title: "朋友圈", style: .default, handler: { [weak self] action in
                Share.share(model, WXSceneTimeline)
                req()
            }))
            actionSheet.addAction(UIAlertAction(title: "微信", style: .default, handler: { [weak self] action in
                Share.share(model, WXSceneSession)
                req()

            }))
            actionSheet.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil))
            
            present(actionSheet, animated: true, completion: nil)
        }
        
        func req() {
            OrderShare.success(orderId: id, success: {
                
            }) { [weak self] msg in
                self?.showError(msg)
            }
        }
    }
    
    @IBAction func back(_ sender: UIButton) {
        navigationController?.popToRootViewController(animated: true)
    }
}
